package com.googlecode.cryptoid;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.Stack;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

abstract class MessageTab extends Activity {
	EditText messageText;
	TextView matrixText;

	public void start(){
		 setContentView(R.layout.messagetab);
		 messageText = (EditText) findViewById(R.id.messagetext);
		 matrixText = (TextView) findViewById(R.id.matrix_name);
		 matrixText.setText( (CharSequence) (getString(R.string.matrix)+ " " + Matrix.name) );
	}
    
    
    public void share(View button){
    	Intent shareIntent = new Intent(Intent.ACTION_SEND);
    	shareIntent.setType("text/plain");
    	shareIntent.putExtra(Intent.EXTRA_TEXT, messageText.getText().toString());
    	startActivity(Intent.createChooser(shareIntent, getString(R.string.share)));
    }
    

    public void toMatrices(View button){
    	EditMatrix.newMatrix = false;
    	ViewMessage.newMessage = false;
    	Intent matrixList = new Intent(this, MatrixList.class);
    	startActivity(matrixList);
    	finish();
    }


	public boolean toMessageList() {
		boolean inputReady = true;
		int len = 0;
		Stack<String> messagesStack = new Stack<String>();
	
		
			ObjectInputStream input;
			try {
				input = new ObjectInputStream(openFileInput(".msglist"));
				if(inputReady){
					String[] messagesIn = (String[]) input.readObject();
					input.close();
				
					len = messagesIn.length;
					
					for(int i = 1; i <= len; i++)
						messagesStack.add(messagesIn[len - i]);
					
				}
			}
			  catch (FileNotFoundException e) {
				inputReady = false;
			} catch (StreamCorruptedException e) {
				return false;
			} catch (IOException e) {
				return false;
			} catch (ClassNotFoundException e) {
				return false;
			} 
		
			
			
			if(!messagesStack.contains(ViewMessage.raw)){
				
				String[] messagesOut = new String[len+1];
				for(int i = 0; i < len; i ++)
					messagesOut[i] = messagesStack.pop();
				messagesOut[len] = ViewMessage.raw;
				
				ObjectOutputStream output;
				try {
					output = new ObjectOutputStream(openFileOutput(".msglist", MODE_PRIVATE));
					output.writeObject(messagesOut);
					output.close();
				} catch (FileNotFoundException e) {
					return false;
				} catch (IOException e) {
					return false;
				}
			}
			
			return true;
			
			
	}
    
    
    
    
}
